package com.zuoye.day11;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class DateDemo {
    public static void main(String[] args) throws ParseException {
        //1. 获得当前时间
        Calendar calendar = Calendar.getInstance();
        System.out.println("获得当前时间:" + calendar);
        //2. 获得2天以后的日期
        calendar.add(Calendar.DATE, +2);
        Date date = calendar.getTime();
        System.out.println("2天以后的日期: " + date);
        //3. 获得3天前的日期
        Calendar calendar1 = Calendar.getInstance();
        calendar1.add(Calendar.DATE, -3);
        Date date1 = calendar1.getTime();
        System.out.println("3天前的日期: " + date1);
        //4. 将字符串"2022/7/21 19:30" 转换成日期对象
        String dateStr = "2022/7/21 19:30";
        DateFormat dateFormat = new SimpleDateFormat("yyyy/M/dd HH:mm");
        try {
            Date date2 = dateFormat.parse(dateStr);
            System.out.println(date2);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        //5.比较两天日期对象date  相差的天数

        String date111 = "2022-8-1";
        String date2 = "2022-6-1";
        SimpleDateFormat formate = new SimpleDateFormat("yyyy-MM-dd");
        Date date3 = formate.parse(date111);
        Date date4 = formate.parse(date2);

        int difnum = differenceDays(date3,date4);
        System.out.println(difnum);

    }
    public static int differenceDays(Date date111,Date date2){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date111);
        int day1 = calendar.get(Calendar.DAY_OF_YEAR);
        calendar.setTime(date2);
        int day2 = calendar.get(Calendar.DAY_OF_YEAR);
        return day1 - day2;

    }

}

